package com.library.management.service.security;

import com.library.management.service.token.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String TOKEN_KEY_PREFIX = "token:";

    @Override
    public void storeToken(String username, String token, long expiration) {
        String key = TOKEN_KEY_PREFIX + username;
        System.out.println("存储token到Redis，key: " + key + ", expiration: " + expiration + "秒");
        redisTemplate.opsForValue().set(key, token, expiration, TimeUnit.SECONDS);
    }

    @Override
    public String getToken(String username) {
        String key = TOKEN_KEY_PREFIX + username;
        Object value = redisTemplate.opsForValue().get(key);
        System.out.println("从Redis获取token，key: " + key + ", value: " + value);
        return value != null ? value.toString() : null;
    }

    @Override
    public boolean validateToken(String username, String token) {
        String storedToken = getToken(username);
        boolean isValid = storedToken != null && storedToken.equals(token);
        System.out.println("验证token，username: " + username + ", isValid: " + isValid);
        return isValid;
    }

    @Override
    public void deleteToken(String username) {
        String key = TOKEN_KEY_PREFIX + username;
        System.out.println("从Redis删除token，key: " + key);
        redisTemplate.delete(key);
    }

    @Override
    public void refreshTokenExpiration(String username, long expiration) {
        String key = TOKEN_KEY_PREFIX + username;
        redisTemplate.expire(key, expiration, TimeUnit.SECONDS);
    }
} 